﻿using GalaSoft.MvvmLight.Command;
using JiveMessenger.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.ObjectModel;
using JiveMessenger.CustomEventArgs;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;

namespace JiveMessenger.CustomControls
{
    /// <summary>
    /// Interaction logic for EmoticonControl.xaml
    /// </summary>
    public partial class EmoticonControl : UserControl
    {
        private bool _cleanupEmoticons;
        public RelayCommand<IEmoticon> ClickEmoticonCommand { get; private set; }

        public static readonly RoutedEvent AddEmoticonEvent = EventManager.RegisterRoutedEvent(
"AddEmoticon", RoutingStrategy.Bubble, typeof(RoutedEventArgs), typeof(EmoticonControl));
        public event RoutedEventHandler AddEmoticon
        {
            add { AddHandler(AddEmoticonEvent, value); }

            remove { RemoveHandler(AddEmoticonEvent, value); }
        }



        // Provide CLR accessors for the event
        public event RoutedEventHandler ClickEmoticon
        {
            add { AddHandler(ClickEmoticonEvent, value); }
            remove { RemoveHandler(ClickEmoticonEvent, value); }
        }

        // Using a RoutedEvent
        public static readonly RoutedEvent ClickEmoticonEvent = EventManager.RegisterRoutedEvent(
            "ClickEmoticon", RoutingStrategy.Bubble, typeof(AddEditEmoticonEventArgs), typeof(EmoticonControl));



        // Provide CLR accessors for the event
        public event RoutedEventHandler EditEmoticon
        {
            add { AddHandler(EditEmoticonEvent, value); }
            remove { RemoveHandler(EditEmoticonEvent, value); }
        }

        // Using a RoutedEvent
        public static readonly RoutedEvent EditEmoticonEvent = EventManager.RegisterRoutedEvent(
            "EditEmoticon", RoutingStrategy.Bubble, typeof(AddEditEmoticonEventArgs), typeof(EmoticonControl));



        public ObservableCollection<JiveDefaultEmoticonModel> DefaultEmoticons
        {
            get { return (ObservableCollection<JiveDefaultEmoticonModel>)GetValue(DefaultEmoticonsProperty); }
            set { SetValue(DefaultEmoticonsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DefaultEmoticons.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DefaultEmoticonsProperty =
            DependencyProperty.Register("DefaultEmoticons", typeof(ObservableCollection<JiveDefaultEmoticonModel>), typeof(EmoticonControl), new PropertyMetadata(null));



        public ObservableCollection<JiveCustomEmoticonModel> CustomEmoticons
        {
            get { return (ObservableCollection<JiveCustomEmoticonModel>)GetValue(CustomEmoticonsProperty); }
            set { SetValue(CustomEmoticonsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CustomEmoticons.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CustomEmoticonsProperty =
            DependencyProperty.Register("CustomEmoticons", typeof(ObservableCollection<JiveCustomEmoticonModel>), typeof(EmoticonControl), new PropertyMetadata(null));


        public double EmoticonMaxSize
        {
            get { return (int)GetValue(EmoticonMaxSizeProperty); }
            set { SetValue(EmoticonMaxSizeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for EmoticonMaxSize.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EmoticonMaxSizeProperty =
            DependencyProperty.Register("EmoticonMaxSize", typeof(double), typeof(EmoticonControl), new PropertyMetadata(40.0));




        public bool AnimateEmoticons
        {
            get { return (bool)GetValue(AnimateEmoticonsProperty); }
            set { SetValue(AnimateEmoticonsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for AnimateEmoticons.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AnimateEmoticonsProperty =
            DependencyProperty.Register("AnimateEmoticons", typeof(bool), typeof(EmoticonControl), new PropertyMetadata(true));




        ~EmoticonControl()
        {
            // Debug.WriteLine(DateTime.Now.ToShortTimeString() + " Emoticon control destructed");
        }
        public EmoticonControl()
        {
            InitializeComponent();
            MainGrid.DataContext = this;
            ClickEmoticonCommand = new RelayCommand<IEmoticon>(ClickEmoticonCommandAction);

        }

        private void ClickEmoticonCommandAction(IEmoticon e)
        {
            RaiseEvent(new AddEditEmoticonEventArgs(ClickEmoticonEvent, this, e));
        }

        private void bnCreate_Click(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(AddEmoticonEvent, this));
        }


        private void MenuItemEditEmoticon_Click(object sender, RoutedEventArgs e)
        {
            MenuItem m = (MenuItem)sender;
            RaiseEvent(new AddEditEmoticonEventArgs(EditEmoticonEvent, this, (IEmoticon)m.DataContext));
        }

        private void MenuItemDeleteEmoticon_Click(object sender, RoutedEventArgs e)
        {
            MenuItem m = (MenuItem)sender;
            CustomEmoticons.Remove((JiveCustomEmoticonModel)m.DataContext);
        }

        private void Image_Loaded(object sender, RoutedEventArgs e)
        {
            Image img = (Image)sender;
            if (img.Source == null)
                return;

            var controller = WpfAnimatedGif.ImageBehavior.GetAnimationController(img);

            if (controller != null)
            {
                //  controller.Pause();
                controller.Play();
            }
            else if (AnimateEmoticons)
            {
                this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        WpfAnimatedGif.ImageBehavior.SetAutoStart(img, true);
                        WpfAnimatedGif.ImageBehavior.SetRepeatBehavior(img, System.Windows.Media.Animation.RepeatBehavior.Forever);
                        WpfAnimatedGif.ImageBehavior.SetAnimatedSource(img, img.Source as BitmapSource);
                        Debug.WriteLine("loaded gif");
                    }), System.Windows.Threading.DispatcherPriority.Background);

            }
        }

        private void Image_Unloaded(object sender, RoutedEventArgs e)
        {
            Image img = (Image)sender;
            if (_cleanupEmoticons)
            {
                Debug.WriteLine("Unloaded image " + img.Source);
                WpfAnimatedGif.ImageBehavior.SetAnimatedSource(img, null);
            }
            else
            {
                e.Handled = true;
                var controller = WpfAnimatedGif.ImageBehavior.GetAnimationController(img);

                if (controller != null)
                {
                    controller.Pause();
                }
            }
            //var controller = WpfAnimatedGif.ImageBehavior.GetAnimationController(img);

            //if (controller != null)
            //{
            //    controller.Dispose();
            //}
        }

        internal void Cleanup()
        {
            _cleanupEmoticons = true;
            this.JiveEmoticonControl.CustomEmoticons = null;
            this.JiveEmoticonControl.DefaultEmoticons = null;
            Debug.WriteLine("Cleaned up emoticon control");
        }
    }
}
